package com.ky.facescan.utils;

import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */

public class StringUtils {

    public static boolean isValidNum(String str){
        BigDecimal bd = new BigDecimal(str);
        BigDecimal bdZero = new BigDecimal("0");
        int i = bd.compareTo(bdZero);
        LogUtils.e("StringUtils:"+i);
        //返回的结果是int类型，-1表示小于，0是等于，1是大于
        if(i==1||i==0){
            return true;
        }else{
            return false;
        }
    }

    public static boolean isNullAndZero(String str){
        return str == null ||"".equals(str)|| TextUtils.isEmpty(str)||"0".equals(str)||"0.00".equals(str)||"0.0".equals(str);
    }

    public static boolean isNull(String str){
        return str == null ||"".equals(str)|| TextUtils.isEmpty(str)|| "null".equals(str);
    }

    public static boolean isGone(String str){
        return str == null || TextUtils.isEmpty(str)||"".equals(str)|| str.contains("/");
    }

    /**
     * 进行加法运算
     * @param str1
     * @param str2
     * @return
     */
    public static String add(String str1, String str2){
        LogUtils.e("stub  str2:"+str2);
        BigDecimal bd1 = new BigDecimal(str1);
        BigDecimal bd2 = new BigDecimal(str2);
        // 进行加法运算
        return bd1.add(bd2).toString();
    }

    public static String replacePhone(String str){
        if(!isNull(str)&&str.length()==11){
            String ss = str.substring(0,str.length()-(str.substring(3)).length())+"****"+str.substring(7);
            return ss;
        }
        return str;
    }

    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private final static Pattern IMG_URL = Pattern
            .compile(".*?(gif|jpeg|png|jpg|bmp)");

    private final static Pattern URL = Pattern
            .compile("^(https|http)://.*?$(net|com|.com.cn|org|me|)");

    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

    public final static Pattern phone = Pattern
            .compile("^((1[3-5][0-9])|(1[7-8][0-9]))\\d{8}$");

    /**
     * @return 判断一个时间是不是今天
     */
    public static boolean isToday(long when) {
        android.text.format.Time time = new android.text.format.Time();
        time.set(when);

        int thenYear = time.year;
        int thenMonth = time.month;
        int thenMonthDay = time.monthDay;

        time.set(System.currentTimeMillis());
        return (thenYear == time.year)
                && (thenMonth == time.month)
                && (thenMonthDay == time.monthDay);
    }

    /**
     * @return 判断一个时间是不是昨天
     */
    public static boolean isYesterday(long when) {
        android.text.format.Time time = new android.text.format.Time();
        time.set(when);

        int thenYear = time.year;
        int thenMonth = time.month;
        int thenMonthDay = time.monthDay;

        time.set(System.currentTimeMillis());
        return (thenYear == time.year)
                && (thenMonth == time.month)
                && (time.monthDay - thenMonthDay == 1);
    }

    /**
     * 转化为时间字符串
     *
     * @param time
     * @return
     */
    public static String getTimeForString(long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeStr = sdf.format(date);
        return timeStr;
    }

    /**
     * 转化为时间字符串
     *
     * @param time
     * @return
     */
    public static String getTimeForStringSec(long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String timeStr = sdf.format(date);
        return timeStr;
    }

    /**
     * 转化为时间字符串
     *
     * @param time
     * @return
     */
    public static String getTimeForStringGang(long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String timeStr = sdf.format(date);
        return timeStr;
    }

    /**
     * 时间类型字符串转化为long类型时间
     *
     * @param time
     * @return
     */
    public static long getTimeForLong(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
        Date dt2 = null;
        long lTime = 0;
        try {
            dt2 = sdf.parse(time);
            //继续转换得到秒数的long型
            lTime = dt2.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lTime;
    }

    /**
     * 时间类型字符串转化为long类型时间
     *
     * @param time
     * @return
     */
    public static long getTimeForLong2(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dt2 = null;
        long lTime = 0;
        try {
            dt2 = sdf.parse(time);
            //继续转换得到秒数的long型
            lTime = dt2.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lTime;
    }

    /**
     * 打印流水contentText
     *
     * @param text
     * @param limit
     * @return
     */
    public static String getContentText(String text, int limit) {
        String contentText = "";
//开始输入字符的长度
        int start = limit - text.length();
        for (int i = 1; i <= limit; i++) {
            if (i == start + 1) {
                contentText += text;
                return contentText;
            } else {
                contentText += " ";
            }
        }
        return "";

    }

    public static String doubleForText(Double text) {
        if (text != null) {
            DecimalFormat df = new DecimalFormat("######0.00");
            String format = df.format(text);
            return format;
        }
        return "0.00";
    }

    public static String intFormateText(double text) {
        DecimalFormat df = new DecimalFormat("######0");
        String format = df.format(text);
        return format;
    }

    public static String voiceFormateText(double text) {
        String s = String.valueOf(text);
        String[] split = s.split("\\.");
        String s1 = split[1];
        if (s1.length() == 1) {
            if ("0".equals(s1)) {
                return split[0];
            }
        }
        return s;
    }

    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 测试手机号是否正确
     *
     * @param text
     * @return
     */
    public static boolean testPhoneNum(String text) {
//        String str = "^((13[0-9])|(15[^4,\\D])|(17[0-8])|(18[0-9]))\\d{8}$";
        /*String str = "^((1[3-5][0-9])|(1[7-9][0-9]))\\d{8}$";
        Pattern pattern = Pattern.compile(str);
        Matcher matcher = pattern.matcher(text);
        return matcher.matches();*/
        return text != null && text.length() == 11;
    }

    /**
     * 设置手机号脱敏
     */
    public static String setPhoneDesensitization(String mobile) {
        if (!TextUtils.isEmpty(mobile)) {
            if (mobile.length() == 11) {
                mobile = mobile.substring(0, 3) + "****" + mobile.substring(7, mobile.length());
            }
        }
        return mobile;
    }

    public static <T> ArrayList<T> fromJsonList(String json, Class<T> cls) {
        Gson mGson = new Gson();
        ArrayList<T> mList = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            mList.add(mGson.fromJson(elem, cls));
        }
        return mList;
    }

    public static String getTimeFromHour(double hour) {
        if (hour % 24 == 0d) {
            if (hour / 24 == 1) {
                return "天";
            } else {
                return String.format(Locale.getDefault(), "%.0f天", hour / 24);
            }
        } else {
            if (hour == 1) {
                return "小时";
            } else if (hour % 1 == 0d) {
                return String.format(Locale.getDefault(), "%.0f小时", hour);
            } else {
                return String.format(Locale.getDefault(), "%.1f小时", hour);
            }
        }
    }



    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * @param text
     * @param lenth
     * @return
     */
    public static String setTextLenth(String text, int lenth) {
        if (!TextUtils.isEmpty(text) && text.length() > lenth) {
            text = text.substring(0, lenth) + "...";
        }
        return text;
    }


    /**
     * 字符串长度不够前面或后面补0
     * @param str
     * @param strLength
     * @return
     */
    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        StringBuffer sb = null;
        while (strLen < strLength) {
            sb = new StringBuffer();
            sb.append("0").append(str);// 左(前)补0
            // sb.append(str).append("0");//右(后)补0
            str = sb.toString();
            strLen = str.length();
        }
        return str;
    }

    public static boolean numIs8(String str) {
        int strLen = str.length();
        if(strLen==8){
            return true;
        }else{
            return false;
        }
    }


    /**
     * 判断字符串是0-9的纯数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
//        for (int i = 0; i < str.length(); i++){
//            if (!Character.isDigit(str.charAt(i))){
//                return false;
//            }
//        }
//        return true;

        boolean result=str.matches("[0-9]+");

        if (result == true) {

            System.out.println("该字符串是纯数字");
            return true;

        }else{

            System.out.println("该字符串不是纯数字");
            return false;

        }

    }

    /**
     * 从字符串中取出数字
     * @param str
     * @return
     */
    public static String takeNum(String str){
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return  m.replaceAll("").trim();
    }


    /**
     * 判断是否是百度OCR的问题
     * @param result
     * @return
     */
    public static boolean isBaiduOcrError(String result){
        if(result.contains("Network error")){
            return true;
        }else if(result.contains("网络请求失败")){
            return true;
        }else if(result.contains("Authentication time error")){
            return true;
        }else if(result.contains("设备时间异常")){
            return true;
        }else if(result.contains("Server illegal response")){
            return true;
        }else if(result.contains("服务器返回数据异常")){
            return true;
        }else if(result.contains("Load jni so library error")){
            return true;
        }else if(result.contains("JNI加载异常")){
            return true;
        }else if(result.contains("Server authentication error")){
            return true;
        }else if(result.contains("身份验证错误")){
            return true;
        }else if(result.contains("App identifier unmatch")){
            return true;
        }else if(result.contains("错误的PackageName或者BundleId")){
            return true;
        }else if(result.contains("Server internal error")){
            return true;
        }else if(result.contains("服务器内部错误")){
            return true;
        }
        return false;
    }



}
